package com.atguigu.gmall.mq.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * 采用配置类方式 定义死信队列,死信交换机 绑定关系
 */
@Configuration
public class DeadLetterMqConfig {
    // 声明一些变量

    public static final String exchange_dead = "exchange.dead";

    public static final String routing_dead_1 = "routing.dead.1";
    public static final String routing_dead_2 = "routing.dead.2";

    public static final String queue_dead_1 = "queue.dead.1";
    public static final String queue_dead_2 = "queue.dead.2";


    /**
     * 定义交换机
     */
    @Bean
    public DirectExchange directExchange() {
        //自动删除-当交换机没有绑定队列后交换机是否自动删除
        return new DirectExchange(exchange_dead, true, false);
    }


    /**
     * 设置队列过期时间,将过期消息发送到执行交互机(设置路由键)
     *
     * @return
     */
    @Bean
    public Queue queue1() {
        //参数三:(是否排他)只有声明该队列应用程序使用
        Map<String, Object> args = new HashMap<String, Object>();
        //设置进入该队列 消息TTL时间 单位:秒
        args.put("x-message-ttl", 10000);
        //如果消息超时,发送到指定交换机,按照指定路由键发送
        args.put("x-dead-letter-exchange", exchange_dead);
        args.put("x-dead-letter-routing-key", routing_dead_2);
        return new Queue(queue_dead_1, true, true, false, args);
    }


    /**
     * 交换机跟队列1绑定
     *
     * @return
     */
    @Bean
    public Binding binding1() {
        return BindingBuilder.bind(queue1()).to(directExchange()).with(routing_dead_1);
    }


    /**
     * 声明队列2
     */
    @Bean
    public Queue queue2() {
        //参数三:(是否排他)只有声明该队列应用程序使用
        return new Queue(queue_dead_2, true, true, false);
    }


    /**
     * 交换机跟队列2绑定
     *
     * @return
     */
    @Bean
    public Binding binding2() {
        return BindingBuilder.bind(queue2()).to(directExchange()).with(routing_dead_2);
    }
}
